<template>
  <div class="chat-app">
    <el-row class="chat-row">
      <!-- 左侧好友列表 -->
      <el-col :span="6" class="sidebar">
        <div class="online-users">
          <h3>在线用户</h3>
          <ul>
            <li
              v-for="user in oluser"
              :key="user.id"
              @click="selectUser(user.id)"
              :class="{ selected: user.id === selectUserId }"
            >
              <img :src="user.img" alt="头像" />
              <span>{{ user.name }}</span>
            </li>
          </ul>
        </div>
      </el-col>

      <!-- 右侧聊天区 -->
      <el-col :span="18" class="chat-area">
        <div class="chat-header">
          <span>{{ currentUserName }}</span>
        </div>

        <div class="chat-box">
          <div class="messages" ref="messages">
            <div
              v-for="(msg, index) in messages"
              :key="index"
              :class="['message', msg.fromUserId === message.userId ? 'me' : 'other']"
            >
              <strong>{{ getUserName(msg.fromUserId) }}:</strong> {{ msg.context }}
            </div>
          </div>
        </div>

        <div class="input-area">
          <input
            v-model="message.context"
            type="text"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
          />
          <button @click="sendMessage">发送</button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getOnlineUserList, getFriendList, getUserNameById, saveHistory } from "../apis/login";

export default {
  name: "ChatApp",
  data() {
    return {
      websock: null, // WebSocket 实例
      oluser: [], // 在线用户列表
      messages: [], // 聊天记录
      message: { context: "", userId: "" }, // 当前消息输入
      currentUserName: "", // 当前聊天用户名称
      selectUserId: null, // 当前选中的用户ID
    };
  },
  created() {
    // 初始化 WebSocket
    this.initWebSocket();
    // 查询在线用户列表
    this.queryOnlineUser();
  },
  methods: {
    // 初始化 WebSocket 连接
    initWebSocket() {
      this.websock = new WebSocket("ws://localhost:8080/chat");
      this.websock.onopen = () => {
        console.log("WebSocket 连接已建立");
      };
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = (error) => {
        console.error("WebSocket 错误:", error);
      };
      this.websock.onclose = () => {
        console.log("WebSocket 连接关闭");
      };
    },

    // 查询在线用户
    queryOnlineUser() {
      getOnlineUserList().then((res) => {
        this.oluser = res.data.map(user => ({
          id: user.id,
          name: user.name,
          img: user.img,
        }));
      }).catch(error => {
        console.error("获取在线用户失败:", error);
      });
    },

    // 选择聊天用户
    selectUser(userId) {
      this.selectUserId = userId;
      this.message.userId = userId; // 设置当前聊天的目标用户ID
      this.currentUserName = this.getUserName(userId); // 更新当前聊天用户的名称

      // 加载聊天记录
      this.loadMessages(userId);
    },

    // 获取用户名称
    getUserName(userId) {
      const user = this.oluser.find(user => user.id === userId);
      return user ? user.name : "Unknown";
    },

    // 加载消息
    loadMessages(userId) {
      // 模拟从数据库或缓存获取聊天记录
      this.messages = JSON.parse(localStorage.getItem(`chat_${this.message.userId}_${userId}`)) || [];
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    // 滚动到聊天框底部
    scrollToBottom() {
      this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight;
    },

    // 发送消息
    sendMessage() {
      if (this.message.context.trim() !== "") {
        const newMessage = {
          fromUserId: this.message.userId,
          toUserId: this.selectUserId,
          context: this.message.context,
        };
        this.messages.push(newMessage);
        this.saveMessageHistory(newMessage);
        this.websock.send(JSON.stringify(newMessage));

        // 清空输入框并滚动到底部
        this.message.context = "";
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } else {
        alert("请输入消息");
      }
    },

    // 保存聊天历史记录
    saveMessageHistory(data) {
      saveHistory(data).then((res) => {
        console.log("历史记录保存成功");
      }).catch((error) => {
        console.error("保存历史记录失败:", error);
      });
    },

    // WebSocket 接收到消息时
    websocketonmessage(e) {
      const data = JSON.parse(e.data);
      if (data && data.fromUserId && data.context) {
        this.messages.push({
          fromUserId: data.fromUserId,
          toUserId: data.toUserId,
          context: data.context,
        });
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
  },
};
</script>

<style scoped>
.chat-app {
  display: flex;
  height: 100vh;
  flex-direction: row;
}

.chat-row {
  flex: 1;
  display: flex;
}

.sidebar {
  background-color: #f8f8f8;
  padding: 10px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.online-users {
  font-size: 14px;
}

.online-users h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
}

.online-users ul {
  padding: 0;
  list-style-type: none;
}

.online-users li {
  padding: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.online-users li:hover {
  background-color: #e9f5ff;
}

.online-users li.selected {
  background-color: #d0e7ff;
}

.online-users img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 18px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.chat-box {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.messages {
  margin-bottom: 20px;
}

.message {
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
  margin-bottom: 10px;
}

.message.me {
  background-color: #d1f5d3;
  align-self: flex-end;
  text-align: right;
}

.message.other {
  background-color: #f1f1f1;
  align-self: flex-start;
}

.message strong {
  font-weight: bold;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
}

.input-area button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

.input-area button:hover {
  background-color: #0056b3;
}
</style>
